package com.Education.Controller;

import com.Education.pojo.User;
import com.Education.server.UserService;
import com.Education.util.JwtUtils;
import com.Education.util.ResponseUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ServerErrorException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class HelloController {
    private final Log logger = LogFactory.getLog(UserLoginController.class);

    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    @Autowired
    UserService userService;

    @Autowired
    JwtUtils jwtUtils;

    /**
     * 微信登录
     *
     * @param user     用户
     * @return 登录结果
     */
    @RequestMapping(value = "/userlogin111111111", method = RequestMethod.POST)
    public Object loginByWeixin(@RequestBody User user, HttpServletRequest request, HttpServletResponse resp) throws IOException {

        String username = user.getUsername();
        String password = user.getPassword();

        logger.info("============>>username:"+username+"  =======>>password:"+password);

        System.out.println("SessionId:"+request.getSession().getId());

        /*
        //不使用jwt时的校验部分
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
            Session session = subject.getSession();
            session.setAttribute("subject", subject);
            //return  ResponseUtil.ok("登录成功");
        } catch (AuthenticationException e) {
            return  ResponseUtil.fail(-1,"登录失败");
        }
        */


        //先从数据库判断用户是否存在
        User user2 = userService.getUser(username,password);
        if(user2 != null ){
            //返回jwt信息
            //String jwt = jwtUtils.generateToken(user.getUsername());
            String jwt = jwtUtils.generateToken(username);
            resp.setHeader("Authorization", jwt);
            resp.setHeader("Access-control-Expose-Headers", "Authorization");

            Map<Object, Object> result = new HashMap<Object, Object>();
            result.put("message","登录成功");
            return ResponseUtil.ok(result);

        }else {
            //若用户不存在，则去教务网站尝试登录
            //1.获取连接客户端工具(创建httpClient实例)
            //CloseableHttpClient httpClient = HttpClients.createDefault();
            CookieStore cookieStore = new BasicCookieStore();
            CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
            //2.声明post请求
            HttpPost httpPost = new HttpPost("http://jw.jluzh.edu.cn/xtgl/login_slogin.html");
            //3.设置参数
            List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
            parameters.add(new BasicNameValuePair("yhm", username));
            parameters.add(new BasicNameValuePair("mm", password));

            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters,"UTF-8");

            //设置请求和传输超时时间
            //RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
            //构建超时等配置信息
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(2000) //建立socket链接超时时间
                    .setConnectionRequestTimeout(1000) //从连接池中取的连接的最长时间
                    .setSocketTimeout(10 *1000) //socket连接建立成功, 数据传输响应超时
                    //.setStaleConnectionCheckEnabled(true) //提交请求前测试连接是否可用
                    .build();

            //浏览器Agent
            httpPost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");
            // 传输的类型
            //httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            httpPost.addHeader("Connection","keep-alive");
            httpPost.setEntity(formEntity);
            httpPost.setConfig(requestConfig);

            //5.发送请求，返回内容
            CloseableHttpResponse response = httpClient.execute(httpPost);

            logger.info("StatusCode:"+response.getStatusLine().getStatusCode());
            logger.info("response1:"+response);

            //重定向后的地址
            String edirectLocations = response.getFirstHeader("Location").getValue();
            System.out.println("edirectLocations:"+"http://jw.jluzh.edu.cn"+edirectLocations);

            Document document = Jsoup.parse(EntityUtils.toString(response.getEntity()));

            //System.out.println("document:"+document);

            if(response.getStatusLine().getStatusCode()==200){
                HttpEntity entity = response.getEntity();
                String string = EntityUtils.toString(entity, "utf-8");
                System.out.println("entity:"+string);
            }
            if(response.getStatusLine().getStatusCode()==302){
                if ("/xtgl/index_initMenu.html".equals(response.getFirstHeader("Location").getValue())) {

                    httpPost = new HttpPost("http://jw.jluzh.edu.cn"+response.getFirstHeader("Location").getValue());
                    response = httpClient.execute(httpPost);
                    document = Jsoup.parse(EntityUtils.toString(response.getEntity()));
                    System.out.println("response2:"+response);
                    if (response.getStatusLine().getStatusCode() == 200 && document.title().equals("吉林大学珠海学院教学综合信息服务平台")) {
                        //登录我的门户成功
                        //return LoginCasSystem(httpClient, user);
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            //System.out.println("--------------------------------------");
                            //System.out.println("document2: " + document);
                            //System.out.println("--------------------------------------");
                        }

                        System.out.println(response.getStatusLine().getStatusCode());
                        if(response.getStatusLine().getStatusCode()==200){
                            //httpPost = new HttpPost("http://jw.jluzh.edu.cn/kbcx/xskbcx_cxXskbcxIndex.html?gnmkdm=N2151&layout=default&su=04172201");
                            httpPost = new HttpPost("http://jw.jluzh.edu.cn/kbcx/xskbcx_cxXsKb.html?gnmkdm=N2151&su=04172201");

                            //3.设置参数
                            List<NameValuePair> parameters2 = new ArrayList<NameValuePair>(0);
                            parameters.add(new BasicNameValuePair("xnm", "2019"));
                            parameters.add(new BasicNameValuePair("xqm", "3"));
                            UrlEncodedFormEntity formEntity2 = new UrlEncodedFormEntity(parameters,"UTF-8");
                            httpPost.setEntity(formEntity2);

                            response = httpClient.execute(httpPost);
//                        document = Jsoup.parse(EntityUtils.toString(response.getEntity()));
//                        System.out.println(response.getStatusLine().getStatusCode());
                            System.out.println("response3:"+response);
//                        System.out.println("document3: " + document);
                            HttpEntity entity3 = response.getEntity();
                            String result = EntityUtils.toString(entity3, "utf-8");
                            System.out.println("entity3:"+result);
                            JSONObject jsonObject = JSONObject.parseObject(result);
                            System.out.println("1"+jsonObject.getString("kbList"));


                            //System.out.println(jsonObject);
                            //json格式化输出
                            ObjectMapper mapper = new ObjectMapper();
                            System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject));

                            //String pretty = JSON.toJSONString(jsonObject, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat);
                            // System.out.println(pretty);


                        }

                    }
                } else {
                    throw new ServerErrorException("教务系统异常");
                }
            }

            String JSESSIONID = null;
            String route = null;
            List<Cookie> cookies = cookieStore.getCookies();
            for (int i = 0; i < cookies.size(); i++) {
                if (cookies.get(i).getName().equals("JSESSIONID")) {
                    Cookie c = cookies.get(i);
                    System.out.println(cookies.get(i));
                    JSESSIONID = cookies.get(i).getValue();
                }
                if (cookies.get(i).getName().equals("route")) {
                    route = cookies.get(i).getValue();
                }
            }

            System.out.println("cookies:"+cookies);
            System.out.println("JSESSIONID:"+JSESSIONID);
            System.out.println("route:"+route);

            //6.关闭资源
            response.close();
            httpClient.close();


            //返回jwt信息
            String jwt = jwtUtils.generateToken(username);
            response.setHeader("Authorization", jwt);
            response.setHeader("Access-control-Expose-Headers", "Authorization");

            Map<Object, Object> result = new HashMap<Object, Object>();
            result.put("message","登录成功");
            return ResponseUtil.ok(result);
        }


    }
}
